"""
backend/app.py - 修复版
"""
from flask import Flask, jsonify, render_template, send_from_directory, abort
import sqlite3
import json
import os
import logging
from pathlib import Path

# 初始化配置
app = Flask(__name__, static_folder='static')
app.config.update(
    DATABASE=Path(__file__).parent / 'static' / 'image.db',
    IMAGE_DIR=Path(__file__).parent / 'static' / 'images',
    MAX_TAGS=10
)

# 日志配置
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('ImageServer')

# 数据库连接
def get_db_connection():
    conn = sqlite3.connect(app.config['DATABASE'])
    conn.row_factory = sqlite3.Row
    return conn

def init_db():
    with app.app_context(), get_db_connection() as conn:
        # 创建表
        conn.execute('''
            CREATE TABLE IF NOT EXISTS images (
                id INTEGER PRIMARY KEY,
                file_name TEXT UNIQUE NOT NULL,
                type INTEGER NOT NULL CHECK(type BETWEEN 1 AND 3),
                category INTEGER CHECK(category BETWEEN 1 AND 4),
                title TEXT,
                source_info TEXT,
                tags TEXT,  -- 移除JSON约束
                likes INTEGER DEFAULT 0,
                downloads INTEGER DEFAULT 0
            )
        ''')


# 路由配置
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/images')
def get_images():
    try:
        conn = get_db_connection()
        images = conn.execute('SELECT * FROM images ORDER BY id DESC').fetchall()
        return jsonify([dict(img) for img in images])
    except Exception as e:
        logger.error(f"Error: {e}")
        return jsonify(error="Server error"), 500
    finally:
        conn.close()
# 统计下载
@app.route('/api/download/<int:image_id>')
def download_image(image_id):
    try:
        conn = get_db_connection()
        
        # 获取文件名并更新下载次数
        img = conn.execute(
            'SELECT file_name FROM images WHERE id = ?',
            (image_id,)
        ).fetchone()
        
        if not img:
            abort(404)
            
        conn.execute(
            'UPDATE images SET downloads = downloads + 1 WHERE id = ?',
            (image_id,)
        )
        conn.commit()
        
        return send_from_directory(app.config['IMAGE_DIR'], img['file_name'], as_attachment=True)
    except Exception as e:
        logger.error(f"Download error: {e}")
        abort(500)
    finally:
        conn.close()

# 在路由配置部分添加以下接口
@app.route('/api/images/<int:image_id>')
def get_single_image(image_id):
    """获取单张图片详细信息的接口"""
    try:
        conn = get_db_connection()
        img = conn.execute(
            'SELECT * FROM images WHERE id = ?', 
            (image_id,)
        ).fetchone()
        
        if not img:
            logger.warning(f"Image {image_id} not found")
            abort(404)
            
        return jsonify(dict(img))
    except sqlite3.Error as e:
        logger.error(f"Database error: {e}")
        return jsonify(error="Database error"), 500
    finally:
        conn.close()

@app.route('/static/images/<path:filename>')
def serve_image(filename):
    return send_from_directory(app.config['IMAGE_DIR'], filename)

if __name__ == '__main__':
    app.config['IMAGE_DIR'].mkdir(exist_ok=True)
    init_db()
    app.run(debug=True)